package com.dd.ent.car.common.player;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.ent.car.R;
import com.pp.ent.base.log.MLog;


/**
 * Author:LiuJianSheng
 * Date:2016/6/2
 */
public class MediaPlayerControllerView extends FrameLayout implements MediaPlayerStateChangeListener {
    private static final String TAG = "MediaPlayerControllerView";

//    public static final int TYPE_AUTO_PLAY = 1;
//    public static final int TYPE_SHORT_VIDEO_FEED = 2;
//    public static final int TYPE_SHORT_VIDEO_DETAIL = 3;

    private static final int WHAT_HIDE_CONTROLLER = 0x01;
    private static final int SHOW_DURATION = 2000;

    private ThunderMediaPlayer mMediaPlayer;
    private View mRootView;
    private int mViewType;
    private boolean mIsShowing;

    private View mBtnBack;
    private TextView mTvTitle;//标题文字
    private MediaPlayerLoadingView mLoadingView;//中间的加载View
    private ImageView mPosterView;//loadingView的黑色背景，用于覆盖掉之前的播放图像
    private boolean shouldShowLoadingBackground;//是否需要显示LoadingView的黑色背景
    private ImageView mBtnPlayOrPause;
    private ImageView mBtnPrevPlay;//上一个
    private ImageView mBtnNextPlay;//下一个

    private SeekBar mSeekBar;//进度控制条
    private ProgressBar mProgressBar;//进度显示条，最底部
    private ImageView mBtnFullScreen;//全屏按钮
    private View mShowLayout;//界面展示时，需要展示的View，不包含最底部进度条
    private ImageView mIvVoiceAnimation;//声音动画View

    private TextView mTvPlayTime;//当前播放时长
    private TextView mTvDuration;//视频总时长


    private int mDuration;

    private boolean isTitleShowInSmallScreen = true;//在小屏状态下是否显示title

    private boolean canHide = true;//是否允许切换显示、隐藏状态

    private OnControllerVisiableListener mVisiableListener;

    private OnControllerClickListener mClickListener;


    private boolean shouldShowVoiceAnimationOnPlaying;//是否显示声音播放动画


    private boolean isShowControllerOnIdle;//idle状态是否显示操作页面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_HIDE_CONTROLLER:
                    hide();
                    break;
            }
        }
    };

    public MediaPlayerControllerView(Context context) {
        super(context);
        initView(context);
    }

    public MediaPlayerControllerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MediaPlayerControllerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.media_player_controller_view, this, true);

        mBtnBack = rootView.findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer != null) {
                    mMediaPlayer.onOutFullScreenClick();
                }
            }
        });

        mTvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        updateTitleVisiableInSmallScreen();

        mShowLayout = rootView.findViewById(R.id.show_layout);
        mLoadingView = (MediaPlayerLoadingView) rootView.findViewById(R.id.loading_progress);
        mPosterView = (ImageView) rootView.findViewById(R.id.loading_background);
        mBtnPlayOrPause = (ImageView) rootView.findViewById(R.id.play_or_pause_btn);
        mBtnPlayOrPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer == null) {
                    return;
                }
                MediaPlayerState state = mMediaPlayer.getState();
                if (state == MediaPlayerState.STARTED) {
                    mMediaPlayer.pause(true);
                } else if (state == MediaPlayerState.PAUSED) {
                    mMediaPlayer.start();
                } else {
                    mMediaPlayer.rePlay();
                }
                checkIfLimitSpeed();
            }
        });

        mBtnPrevPlay = (ImageView) rootView.findViewById(R.id.prev_play_btn);
        mBtnPrevPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mClickListener != null) {
                    mClickListener.onClickPrevBtn(v);
                }
            }
        });
        mBtnNextPlay = (ImageView) rootView.findViewById(R.id.next_play_btn);
        mBtnNextPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mClickListener != null) {
                    mClickListener.onClickNextBtn(v);
                }
            }
        });


        mSeekBar = (SeekBar) rootView.findViewById(R.id.seek_bar);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if(mClickListener != null){
                    mClickListener.onProgressChange(fromUser,progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                removeHideMsg();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (canHide) {
                    delayHide();
                }
                mMediaPlayer.safetySeekTo(seekBar.getProgress());
            }
        });
        mProgressBar = (ProgressBar) rootView.findViewById(R.id.progress_bar);

        mTvPlayTime = (TextView) rootView.findViewById(R.id.tv_play_time);
        mTvDuration = (TextView) rootView.findViewById(R.id.tv_duration);

        mBtnFullScreen = (ImageView) rootView.findViewById(R.id.full_screen_btn);
        mBtnFullScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer != null) {
                    mMediaPlayer.toggleFullScreenMode();
                }
            }
        });

        mIvVoiceAnimation = (ImageView) rootView.findViewById(R.id.iv_voice_animation);
        Glide.with(getContext()).load(R.drawable.auto_play_voice).into(mIvVoiceAnimation);

        mRootView = rootView;
    }

    public void setViewType(int type) {
        mViewType = type;
        resetView();
    }

    void resetView() {
        switch (mViewType) {
            case ThunderMediaPlayer.TYPE_AUTO_PLAY:
                showVoiceAnimationView();
                hide();
                break;
            case ThunderMediaPlayer.TYPE_SHORT_VIDEO_FEED:
                hideVoiceAnimationView();
                if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
                    hide();
                }else{
                    show();
                }
                break;
            case ThunderMediaPlayer.TYPE_SHORT_VIDEO_DETAIL:
                hideVoiceAnimationView();
                if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
                    hide();
                }else{
                    show();
                }
                break;
        }
    }



    private void checkIfLimitSpeed() {
//        SpeedLimitHelper speedLimitHelper = SpeedLimitHelper.instance();
//        if (speedLimitHelper.getLimitState() == speedLimitHelper.SPEED_NOT_LIMIT) {
//            speedLimitHelper.limitDownloadSpeed(speedLimitHelper.isLimitDownloadSpeed());
//        }
    }

    private void updatePlayOrPauseBtnIcon() {
        if (mMediaPlayer == null) {
            return;
        }
        if (mMediaPlayer.getState() == MediaPlayerState.STARTED) {
            mBtnPlayOrPause.setImageResource(R.drawable.ic_pause_normal);
        } else {
            mBtnPlayOrPause.setImageResource(R.drawable.ic_play_normal_index);
        }
    }

    public void setMediaPlayer(ThunderMediaPlayer mediaPlayer) {
        this.mMediaPlayer = mediaPlayer;
        updatePlayOrPauseBtnIcon();
        setSeekBarStatus(mMediaPlayer.getState());
        if(mediaPlayer.isPlaying()){
            hide();
        }else {
            show();
        }
    }

    private void updateDuration(int duration) {
        mDuration = duration;
        mProgressBar.setMax(duration);
        mSeekBar.setMax(duration);
        mTvDuration.setText(StringUtil.formatDuration(duration));
    }

    private void showVoiceAnimationView() {
        mIvVoiceAnimation.setVisibility(VISIBLE);
    }

    private void hideVoiceAnimationView() {
        mIvVoiceAnimation.setVisibility(GONE);
    }

    public void show() {
        MLog.debug(TAG,"show--isShowing=" + mIsShowing);
        removeHideMsg();
        mShowLayout.setVisibility(VISIBLE);
        mProgressBar.setVisibility(GONE);
        mIsShowing = true;
        if (mVisiableListener != null) {
            mVisiableListener.onVisiableChange(true);
        }
    }

    private void removeHideMsg() {
        if (mHandler.hasMessages(WHAT_HIDE_CONTROLLER)) {
            mHandler.removeMessages(WHAT_HIDE_CONTROLLER);
        }
    }

    private void delayHide() {
        removeHideMsg();
        mHandler.sendEmptyMessageDelayed(WHAT_HIDE_CONTROLLER, SHOW_DURATION);
    }

    void hide() {
        MLog.debug(TAG,"hide--isShowing=" + mIsShowing);
        removeHideMsg();
        mShowLayout.setVisibility(GONE);
        if (mViewType != ThunderMediaPlayer.TYPE_AUTO_PLAY) {
            mProgressBar.setVisibility(VISIBLE);
        }
        mIsShowing = false;
        if (mVisiableListener != null) {
            mVisiableListener.onVisiableChange(false);
        }
    }

    public void startLoading() {
        mLoadingView.startLoading();
    }

    private void stopLoading() {
        mLoadingView.stopLoading();
    }

    public void toggle() {
        if (mIsShowing) {
            if (canHide) {
                hide();
            }
        } else {
            show();
            if (canHide && mMediaPlayer.isPlaying()) {
                delayHide();
            }
        }
    }


    @Override
    public void onStateChange(MediaPlayerState oldState, MediaPlayerState newState) {
        MLog.debug(TAG, "onStateChange() oldState=" + oldState + " newState=" + newState);
        setSeekBarStatus(newState);
        hideVoiceAnimationView();
        switch (newState) {
            case PLAYBACK_COMPLETED:
                hidePlayOrPauseBtn();

                break;
            case PREPARING:
                canHide = true;
                hidePlayOrPauseBtn();
                startLoading();
                if(shouldShowLoadingBackground){
                    mPosterView.setVisibility(VISIBLE);
                }
                break;
            case LOADING:
            case PREPARED:
                canHide = true;
                hidePlayOrPauseBtn();
                startLoading();
                break;
            case STARTED:
                canHide = true;
                long duration = mMediaPlayer.getDuration();
                if (duration > 0) {
                    updateDuration((int) duration);
                }
                updatePlayOrPauseBtnIcon();
                showPlayOrPauseBtn();
                hide();
                stopLoading();
                if (shouldShowVoiceAnimationOnPlaying) {
                    showVoiceAnimationView();
                }
                break;
            case PAUSED:
            case STOPPED:

                canHide = false;
                stopLoading();
                if(mMediaPlayer.isPrepared()){
                    mPosterView.setVisibility(GONE);
                    mPosterView.setImageDrawable(null);
                }
                if(mViewType != ThunderMediaPlayer.TYPE_AUTO_PLAY){
                    updatePlayOrPauseBtnIcon();
                    showPlayOrPauseBtn();
                    removeHideMsg();
                    show();
                }
                break;
            case IDLE:
                reset();
                updatePlayOrPauseBtnIcon();
                showPlayOrPauseBtn();
//                resetView();
                break;
            case ERROR:
                stopLoading();
                hidePlayOrPauseBtn();
                break;
        }
    }

    public void OnBufferingUpdate(int percent) {
        int progress = mDuration * percent / 100;
        mProgressBar.setSecondaryProgress(progress);
        mSeekBar.setSecondaryProgress(progress);
    }

    private void hidePlayOrPauseBtn() {
        mBtnPlayOrPause.setVisibility(GONE);
    }

    private void showPlayOrPauseBtn() {
        mBtnPlayOrPause.setVisibility(VISIBLE);
    }

    public void reset() {
        if (isShowControllerOnIdle) {
            show();
        }
        stopLoading();
        mProgressBar.setProgress(0);
        mProgressBar.setSecondaryProgress(0);

        mTvPlayTime.setText(StringUtil.formatDuration(0));
        mTvDuration.setText(StringUtil.formatDuration(0));
        mDuration = 0;

        mSeekBar.setProgress(0);
        mSeekBar.setSecondaryProgress(0);
        mPosterView.setImageDrawable(null);
    }

    void setTitleVisiableInSmallScreen(boolean isVisible) {
        isTitleShowInSmallScreen = isVisible;
        updateTitleVisiableInSmallScreen();
    }

    //进入全屏
    void onEnterFullScreen() {
        mTvTitle.setVisibility(VISIBLE);
        mBtnBack.setVisibility(VISIBLE);
        mBtnFullScreen.setImageResource(R.drawable.ic_suitscreen_selector);
    }

    //退出全屏
    void onOutFullScreen() {
        updateTitleVisiableInSmallScreen();
        mBtnBack.setVisibility(GONE);
        mBtnFullScreen.setImageResource(R.drawable.ic_fullscreen_selector);
    }

    private void updateTitleVisiableInSmallScreen() {
        if (isTitleShowInSmallScreen) {
            mTvTitle.setVisibility(VISIBLE);
        } else {
            mTvTitle.setVisibility(GONE);
        }
    }

    void setTitle(String title) {
        mTvTitle.setText(title);
    }

    public void setVisiableListener(OnControllerVisiableListener listener) {
        this.mVisiableListener = listener;
    }

    public void onPlayPositionChange(int newPosition) {
        if (newPosition >= 0) {
            mProgressBar.setProgress(newPosition);
            mSeekBar.setProgress(newPosition);
            mTvPlayTime.setText(StringUtil.formatDuration(newPosition));
            if (newPosition > 0) {
                startHidePoster();
            }
        }
    }

    public interface OnControllerVisiableListener {
        void onVisiableChange(boolean isVisible);
    }

    public void setPrevPlayBtnVisiable(boolean isVisible) {
        if (isVisible) {
            mBtnPrevPlay.setVisibility(VISIBLE);
        } else {
            mBtnPrevPlay.setVisibility(GONE);
        }
    }

    public void setNextPlayBtnVisiable(boolean isVisible) {
        if (isVisible) {
            mBtnNextPlay.setVisibility(VISIBLE);
        } else {
            mBtnNextPlay.setVisibility(GONE);
        }
    }



    private void setSeekBarStatus(MediaPlayerState state) {
        mSeekBar.setEnabled(!(state == MediaPlayerState.IDLE || state == MediaPlayerState.PREPARING));
    }

    public void setOnControllerClickListener(OnControllerClickListener listener) {
        this.mClickListener = listener;
    }


    public boolean isShowing() {
        return mIsShowing;
    }

    public void setShouldShowVoiceAnimationOnPlaying(boolean shouldShowVoiceAnimationOnPlaying) {
        this.shouldShowVoiceAnimationOnPlaying = shouldShowVoiceAnimationOnPlaying;
    }

    public void setShowControllerOnIdle(boolean isShowControllerOnIdle) {
        this.isShowControllerOnIdle = isShowControllerOnIdle;
    }


    public void setShouldShowLoadingBackground(boolean shouldShowLoadingBackground) {
        this.shouldShowLoadingBackground = shouldShowLoadingBackground;
    }

    public void setPoster(String poster){
        if (TextUtils.isEmpty(poster)) {
            mPosterView.setImageDrawable(null);
        } else {
            //ChoicenessUtils.displayImage(poster, mPosterView);
        }
        mPosterView.setVisibility(VISIBLE);
    }

    private void startHidePoster(){
        if(mPosterView.getVisibility() == View.VISIBLE){
            Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.media_player_poster_hide_animation);
            animation.setDuration(200);
            mPosterView.setVisibility(GONE);
            mPosterView.startAnimation(animation);
        }
    }
}
